<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <div style="margin-left: 30px; margin-top: 30px">
    <form action="">
      {% csrf_token %}
    <h3>用户注册</h3>
    <p>用户ID：<input type="text" name="userId" value="29"></p>
    <p>相册ID：<input type="password" name="albumId" value="1"></p>
    <p>邮箱：<input type="text" name="email" ></p>
      <input id="avatar" type="text" value="user.png" name="avatar" style="width: 400px"> {# 实际应用中要将该input标签隐藏，display:none; #}
      <p><input type="submit" value="注册"></p>
      </form>
    <div style="position: absolute; top: 85px; left: 300px;">
    <input id="avatarSlect" type="file" style="position: absolute;float: left; z-index: 10; opacity: 0;width: 100px; height: 100px;">
    <img id="avatarPreview" src="user.png" title="点击更换图片" style="position: absolute; z-index: 9; float: left; width: 100px; height: 100px">
      </div>
  </div>
</body>
<script src="jquery-1.11.0.min.js"></script>
<script>
  $(function () {
      bindAvatar();
 });
  function bindAvatar() {
      if(window.URL.createObjectURL){
        bindAvatar3();
      }else if(window.FileReader){
        bindAvatar2();
      }else {
        bindAvatar1();
      }
 }
  /*Ajax上传至后台并返回图片的url*/
  function bindAvatar1() {
    $("#avatarSlect").change(function () {
    var csrf = $("input[name='csrfmiddlewaretoken']").val();
    var formData=new FormData();
    formData.append("csrfmiddlewaretoken",csrf);
    formData.append('avatar', $("#avatarSlect")[0].files[0]);  /*获取上传的图片对象*/
    $.ajax({
      url: 'http://localhost:8013/api-event/v2/web/event/album/uploadEventImages',
          type: 'POST',
          data: formData,
          contentType: false,
          processData: false,
          success: function (args) {
        console.log(args);  /*服务器端的图片地址*/
              $("#avatarPreview").attr('src','/'+args);  /*预览图片*/
              $("#avatar").val('/'+args);  /*将服务端的图片url赋值给form表单的隐藏input标签*/
     }
      })
 })
  }
  /*window.FileReader本地预览*/
  function bindAvatar2() {
    console.log(2);
       $("#avatarSlect").change(function () {
           var obj=$("#avatarSlect")[0].files[0];
           var fr=new FileReader();
           fr.onload=function () {
               $("#avatarPreview").attr('src',this.result);
               console.log(this.result);
               $("#avatar").val(this.result);
      };
      fr.readAsDataURL(obj);
    })
 }
 /*window.URL.createObjectURL本地预览*/
 function bindAvatar3() {
   console.log(3);
      $("#avatarSlect").change(function () {
          var obj=$("#avatarSlect")[0].files[0];
          var wuc=window.URL.createObjectURL(obj);
           $("#avatarPreview").attr('src',wuc);
           $("#avatar").val(wuc);

   })
 }
</script>
</html>